/**
 * 
 */
package com.googlecode.xcarve.router;

import java.util.List;

import org.springframework.util.CollectionUtils;

import com.googlecode.xcarve.object.RPCRequest;
import com.googlecode.xcarve.transport.Client;

/**
 * 
 * @author duxinyun
 * 2015-01-30
 */
public abstract class AbstractRouter implements Router{
	
	@Override
	public Client select(List<? extends Client> list, RPCRequest request) {
		if(CollectionUtils.isEmpty(list)){
			return null;
		}else if(list.size() == 1){
			return list.get(0);
		}
		Object[] args = request.getArguments();
		String servicekey = null;
		if(args != null && args.length > 0){
			servicekey = toKey(args);
		}else{
			servicekey = request.getService().getName();
		}
		return doSelect(list, request.getService().getName(), servicekey);
	}

	 private String toKey(Object[] args) {
         StringBuilder buf = new StringBuilder();
         for (int i=0; i< 4 ; i++) {
             if (i >= 0 && i < args.length) {
                 buf.append(args[i]);
             }
         }
         return buf.toString();
     }
	
	abstract Client doSelect(List<? extends Client> list,String service, String hashKey);
	
}
